package com.ctc.test;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.ctc.CRC;
import com.ctc.CTCClientConnState;
import com.ctc.CTCEvent;
import com.ctc.CTCSlave;
import com.ctc.test.fragment.BaseFragment;

import androidx.annotation.NonNull;

public class SlaveFragment extends BaseFragment implements CTCEvent.ISlave
{
    /** 主设备产品ID */
    private TextView tvMasterProductID;
    /** 主设备ID */
    private TextView tvMasterDeviceID;
    /** 从设备产品ID */
    private TextView tvSlaveProductID;
    /** 从设备ID */
    private TextView tvSlaveDeviceID;
    /** 主设备投币数量 */
    private TextView tvMasterCoinIn;
    /** 连接状态 */
    private TextView tvConnectState;

    /** 打开串口 */
    private Button btnOpenSerial;
    /** 关闭串口 */
    private Button btnCloseSerial;
    /** 氛围事件 */
    private Button btnAtmosphere;
    /** 物理投币 */
    private Button btnPhysicsCoinIn;
    /** 出票 */
    private Button btnOutTicket;
    /** 变更状态 */
    private Button btnChangeState;
    /**
     * 主设备投币数量
     */
    private long masterCoinIn;
    /** 从设备 */
    private CTCSlave ctcSlave;
    /** 从设备产品ID */
    private long slaveProductID = 1;
    /** 从设备ID */
    private byte[] slaveDeviceID = new byte[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        if (bindView == null)
        {
            bindView = inflater.inflate(R.layout.fragment_slave, container, false);
            initMsgList(R.id.fragment_slave_list_msg);
            initSerialSpinner(R.id.fragment_slave_spinner_serial);
            tvMasterProductID = bindView.findViewById(R.id.fragment_slave_tv_masterProductID);
            tvMasterDeviceID = bindView.findViewById(R.id.fragment_slave_tv_masterDeviceID);
            tvSlaveProductID = bindView.findViewById(R.id.fragment_slave_tv_slaveProductID);
            tvSlaveDeviceID = bindView.findViewById(R.id.fragment_slave_tv_slaveDeviceID);
            tvConnectState = bindView.findViewById(R.id.fragment_slave_tv_connectState);
            tvMasterCoinIn = bindView.findViewById(R.id.fragment_slave_tv_masterCoinIn);
            //
            btnOpenSerial = bindView.findViewById(R.id.fragment_slave_btn_openSerial);
            btnCloseSerial = bindView.findViewById(R.id.fragment_slave_btn_closeSerial);
            btnAtmosphere = bindView.findViewById(R.id.fragment_slave_btn_atmosphere);
            btnPhysicsCoinIn = bindView.findViewById(R.id.fragment_slave_btn_physicsCoinIn);
            btnOutTicket = bindView.findViewById(R.id.fragment_slave_btn_outTicket);
            btnChangeState = bindView.findViewById(R.id.fragment_slave_btn_changeState);
            //
            btnOpenSerial.setOnClickListener(v -> {
                String serialPort = (String) spinnerSerial.getSelectedItem();
                ctcSlave = new CTCSlave((byte) 1, serialPort, slaveProductID, slaveDeviceID);
                ctcSlave.setListener(this);
                ctcSlave.open();
                v.setEnabled(false);
            });
            btnAtmosphere.setOnClickListener(v -> {
                ctcSlave.sendAtmosphere((byte) 0, (byte) 0, 100);
            });
            btnPhysicsCoinIn.setOnClickListener(v -> {
                ctcSlave.sendPhysicalReport((byte) 0, 1);
            });
            btnOutTicket.setOnClickListener(v -> {
                ctcSlave.sendReward((byte) 0, 10);
            });
            btnChangeState.setOnClickListener(v -> {
                if (ctcSlave.getSlaveState() == 0)
                {
                    ctcSlave.changeState((byte) 1, 1);
                }
                else
                {
                    ctcSlave.changeState((byte) 0, 0);
                }
            });
            btnCloseSerial.setOnClickListener(v -> {
                ctcSlave.close();
                v.setEnabled(false);
                btnOpenSerial.setEnabled(true);
                instEnable(false);
                tvConnectState.setTextColor(Color.BLACK);
            });
            btnCloseSerial.setEnabled(false);
            instEnable(false);
            tvSlaveProductID.setText(String.format("SlaveProductID:%s", slaveProductID));
            tvSlaveDeviceID.setText(String.format("SlaveDeviceID:%s", CRC.toHexStringTrim(slaveDeviceID)));
        }
        return bindView;
    }

    private void instEnable(boolean enable)
    {
//        btnAtmosphere.setEnabled(enable);
//        btnPhysicsCoinIn.setEnabled(enable);
//        btnOutTicket.setEnabled(enable);
//        btnChangeState.setEnabled(enable);
    }


    @Override
    public void onMasterStateChange(byte player, byte[] data)
    {
        addMsg(String.format("Master状态变更  %s", data[0]));
    }

    @Override
    public void onMeterRead(byte player)
    {
        byte[] data = new byte[50];
        data[0] = 0;
        System.arraycopy(CRC.uint32ToBytes(10), 0, data, 1, 4);
        ctcSlave.rspMeterRead(data);
    }

    @Override
    public void onQueryCoin(byte player)
    {
        ctcSlave.rspQueryCoin(55);
    }

    @Override
    public void onCoinIn(byte player, byte[] data)
    {
        long num = CRC.bytesToUint32(data[0], data[1], data[2], data[3]);
        masterCoinIn += num;
        byte[] memberID = CRC.subByteData(data, 4, 16);
        byte[] orderID = CRC.subByteData(data, 20, 16);
        addMsg(String.format("收到卡头投币:%s-%s-%s", num, CRC.toHexStringTrim(memberID), CRC.toHexStringTrim(orderID)));
        ctcSlave.rspCoinIn(data[0], orderID);
        bindView.post(() -> {
            tvMasterCoinIn.setText(String.format("MasterCoinIn:%s", masterCoinIn));
        });

    }

    @Override
    public void onHandshake(byte player, byte[] data)
    {
        bindView.post(() -> {
            long masterProductID = CRC.bytesToUint32(data[0], data[1], data[2], data[3]);
            byte[] masterDeviceID = new byte[16];
            System.arraycopy(data, 4, masterDeviceID, 0, 16);
            int masterVersion = CRC.bytesToUint16(data[20], data[21]);
            addMsg(String.format("MasterVersion:%s", masterVersion));
            tvMasterProductID.setText(String.format("MasterProductID:%s", masterProductID));
            tvMasterDeviceID.setText(String.format("MasterDeviceID:%s", CRC.toHexStringTrim(masterDeviceID)));
        });
    }

    @Override
    public void onSetCoinPrice(byte player, byte[] data)
    {
        int num = CRC.bytesToUint16(data);
        addMsg(String.format("设置每局币数:%s", num));
    }

    @Override
    public void onSelectChannel(byte player, byte[] data)
    {
        addMsg(String.format("通道选择:%s", CRC.toHexStringTrim(data)));
    }

    @Override
    public void onConnectStateChange(byte player, CTCClientConnState state)
    {
        bindView.post(() -> {
            if (state == com.ctc.CTCClientConnState.Connected)
            {
                tvConnectState.setTextColor(Color.GREEN);
                instEnable(true);
            }
            else
            {
                tvConnectState.setTextColor(Color.RED);
                instEnable(false);
            }
        });
    }

    @Override
    public void onSendSuccess(byte player, byte[] inst, byte[] data)
    {
        addMsg(String.format("发送成功-指令:%s", CRC.toHexStringTrim(inst)));
    }

    @Override
    public void onSendFail(byte state, byte player, byte[] inst, byte[] data)
    {
        addMsg(String.format("发送失败-指令:%s", CRC.toHexStringTrim(inst)));
    }

    @Override
    public void onSerialOpen(byte player, String msg)
    {
        if (msg == null)
        {
            //打开成功
            addMsg("串口打开成功");
            bindView.post(() -> {
                btnCloseSerial.setEnabled(true);
            });
        }
        else
        {
            //打开失败
            bindView.post(() -> {
                btnOpenSerial.setEnabled(true);
                tvConnectState.setTextColor(Color.BLACK);
                instEnable(false);
            });
        }

    }

    @Override
    public void onSerialClose(byte player, String msg)
    {
        //串口被关闭
    }

    @Override
    public void debugLogE(byte player, String msg)
    {
        addMsg(msg);
    }

    @Override
    public void debugLogI(byte player, String msg)
    {
        addMsg(msg);
    }
}